package com.yunzhou.action;

import com.alibaba.fastjson.JSONObject;
import com.yunzhou.common.DataChangeService;
import com.yunzhou.common.DataChangeServiceImpl;
import com.yunzhou.u8.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import weaver.common.util.string.StringUtil;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * MC05、MC06流程
 * update 2022-08-04
 * 修改MC05物料统一取601
 * Created by dengxl
 */

public class createProcurementProcessNewAction implements Action {

    private Log log = LogFactory.getLog(createProcurementProcessNewAction.class.getName());

    public String execute(RequestInfo requestInfo) {

        String requestID = requestInfo.getRequestid();//请求id
        String workflowid = requestInfo.getWorkflowid();//workflowid
        String requestname = requestInfo.getRequestManager().getRequestname();// 请求标题

        log.info("createProcurementProcessNewAction开始====" + requestID + "，workflowid：" + workflowid);

        String ssgs = "";//分公司字段
        String company = "";//分公司
        String liucbh = "";//流程编号
        String shenqr = "";//申请人，workcode
        String shenqrq = "";//申请日期
        String shenqrd = "";//申请单位
        String shenqbm = "";//申请部门
        String shenqyy = "";//申请原因
        String xmmcnew = "";//项目名称
        String caigxm = "";//项目代号
        String xiangmdh = "";//项目号令
        String xmjll = "";//项目经理
        String xiangmzs = "";//项目总师
        String xiangmzsmc = "";//项目总师名称
        String qwdhq = "";//期望到货时间
        String shenhr = "";//审核人

        //获取主表信息
        MainTableInfo mainTableInfo = requestInfo.getMainTableInfo();
        Property[] fields = mainTableInfo.getProperty();
        for (Property property : fields) {
            String name = property.getName();
            String value = property.getValue();
            if (name.equals("ssgs")) {
                ssgs = value;
            }
        }

        mainTableInfo = requestInfo.getMainTableInfo();
        fields = mainTableInfo.getProperty();

        for (Property property : fields) {
            String name = property.getName();
            String value = property.getValue();
            if (name.equals(ssgs)) {
                company = value;
            }
            if (name.equals("liucbh")) {
                liucbh = value;
            }
            if (name.equals("shenqr")) {
                shenqr = value;
            }
            if (name.equals("shenqrq")) {
                shenqrq = value;
            }
            if (name.equals("shenqrd")) {
                shenqrd = value;
            }
            if (name.equals("shenqbm")) {
                shenqbm = value;
            }
            if (name.equals("shenqyy")) {
                shenqyy = value;
            }
            if (name.equals("xmmcnew")) {
                xmmcnew = value;
            }
            if (name.equals("caigxm")) {
                caigxm = value;
            }
            if (name.equals("xiangmdh")) {
                xiangmdh = value;
            }
            if (name.equals("xmjll")) {
                xmjll = value;
            }
            if (name.equals("xiangmzs")) {
                xiangmzs = value;
            }
            if (name.equals("qwdhq")) {
                qwdhq = value;
            }
            if (name.equals("shr")) {
                shenhr = value;
            }
        }
        log.info("转换前公司 （ssgs、company）: " + ssgs + "," + company);
        log.info("主表信息 - requestname:" + requestname + ",caigxm:" + caigxm + ",liucbh:" + liucbh + ",qwdhq:" + qwdhq + ",shenqr:" + shenqr
                + ",shenqrq:" + shenqrq + ",shenqyy:" + shenqyy + ",shenqr:" + shenqr + ",xiangmzs:" + xiangmzs + ",xmjll:" + xmjll + ",xmmcnew:" + xmmcnew);

        //数据转换
        DataChangeService dataChangeService = new DataChangeServiceImpl();
        HashMap ryMap = dataChangeService.getSpecifiedTableMap("hrmresource", "id", "workcode");//人员转换，传workcode
        if (StringUtil.isNotNullAndEmpty(xiangmzs) && xiangmzs != "null") {
            String[] as = xiangmzs.split(",");
            for (int k = 0; k < as.length; k++) {
                if (xiangmzsmc.equals("")) {
                    xiangmzsmc = ryMap.get(as[k]).toString();
                } else {
                    xiangmzsmc += "," + ryMap.get(as[k]);
                }
            }
        }
        HashMap mapGs = dataChangeService.getSpecifiedTableMap("hrmsubcompany", "id", "subcompanycode");//分部集合
        xmmcnew = dataChangeService.getSingleBrowseValue("xmmc", "uf_xmhdb", "id", xmmcnew);

        log.info("传入U8主表信息 - requestname:" + requestname + ",caigxm:" + caigxm + ",liucbh:" + liucbh + ",qwdhq:" + qwdhq + ",ryMap.get(shenqr).toString():" + (shenqr.isEmpty() ? "" : ryMap.get(shenqr).toString())
                + ",shenqrq:" + shenqrq + ",shenqyy:" + shenqyy + ",shenqr:" + shenqr + ",xiangmzs:" + xiangmzs + ",ryMap.get(xmjll).toString():" + (xmjll.isEmpty() ? "" : ryMap.get(xmjll).toString()) + ",xmmcnew:" + xmmcnew);

        workflowid = dataChangeService.getPrimevalID(workflowid);
        log.info("最小版本id : " + workflowid);

        PuAppVouch puApp = new PuAppVouch();
        if (workflowid.equals("317")) {//MC06-研发物料采购申请
            try{
                shenhr = dataChangeService.getCurrentoperatorFromNodeName(requestID, "计划部(审核)");
                log.info("shenhr分别是 : " + shenhr + "," + (shenhr.isEmpty() ? "" : ryMap.get(shenhr).toString()));

                //对应U8主表
                PuAppVouchHead appVouch = new PuAppVouchHead();
                appVouch.setRequestid(requestID);
                appVouch.setBiaoti(requestname);
                appVouch.setCaigxm(caigxm);
                appVouch.setLiucbh(liucbh);
                appVouch.setShenqr((shenqr.isEmpty() ? "" : ryMap.get(shenqr).toString()));
                appVouch.setShenqrq(shenqrq);
                appVouch.setShenqyy(shenqyy);
                appVouch.setXiangmdh(xiangmdh);
                appVouch.setXiangmzs(xiangmzsmc);
                appVouch.setXmjll((xmjll.isEmpty() ? "" : ryMap.get(xmjll).toString()));
                appVouch.setXmmcnew(xmmcnew);
                appVouch.setCcode(liucbh);//流程编码
                appVouch.setShenhr((shenhr.isEmpty() ? "" : ryMap.get(shenhr).toString()));

                //获取流程的明细表数据
                List<JSONObject> list = getJsonArray(requestInfo.getDetailTableInfo().getDetailTable(0));
                log.info("createProcurementProcessNewAction-明细信息 : " + list);
                int j = list.size();
                //赋值明细
                PuAppVouchBody[] appVouchs = new PuAppVouchBody[j];
                for (int i = 0; i < j; i++) {
                    appVouchs[i] = new PuAppVouchBody();
                    appVouchs[i].setWlbm(list.get(i).getString("wlbm"));
                    appVouchs[i].setShul(list.get(i).getString("shul"));
                    appVouchs[i].setDanj(list.get(i).getString("danj"));
                    appVouchs[i].setJine(list.get(i).getString("jine"));
                    appVouchs[i].setCgy((list.get(i).getString("xq").isEmpty() ? "" : ryMap.get(list.get(i).getString("xq")).toString()));
                    appVouchs[i].setBeiz(list.get(i).getString("beiz"));
                    appVouchs[i].setCBusType(list.get(i).getString("ywlx").isEmpty() ? "0" : list.get(i).getString("ywlx"));//0:普通采购,1:委外加工
                    appVouchs[i].setShdz(list.get(i).getString("shdz"));
                    appVouchs[i].setQwdhq(list.get(i).getString("qwdhsj").isEmpty() ? "" : list.get(i).getString("qwdhsj").replace("-" , ""));
                    appVouchs[i].setPuarrivaldate(list.get(i).getString("qwdhrq2").isEmpty() ? "" : list.get(i).getString("qwdhrq2"));
                }

                log.info("转换后公司 : " + mapGs.get(company).toString());
                puApp.setCCompany(mapGs.get(company).toString());//分公司
                puApp.setCptname("研发类物料采购");
                puApp.setAppVouch(appVouch);
                puApp.setAppVouchs(appVouchs);
            }catch (Exception e){
                e.printStackTrace();
                requestInfo.getRequestManager().setMessagecontent("MD06 AppVouch Error "+e.getMessage());
                return FAILURE_AND_CONTINUE;
            }
        } else if (workflowid.equals("316")) {//MC05-生产物料采购申请
            try{
                shenhr = dataChangeService.getCurrentoperatorFromNodeName(requestID, "计划部(审核)");
                log.info("shenhr分别是 : " + shenhr + "," + (shenhr.isEmpty() ? "" : ryMap.get(shenhr).toString()));

                //对应U8主表
                PuAppVouchHead appVouch = new PuAppVouchHead();
                appVouch.setRequestid(requestID);
                appVouch.setBiaoti(requestname);
                appVouch.setLiucbh(liucbh);
                appVouch.setShenqr((shenqr.isEmpty() ? "" : ryMap.get(shenqr).toString()));
                appVouch.setShenqrq(shenqrq);
                appVouch.setShenqyy(shenqyy);
                appVouch.setCcode(liucbh);//流程编码
                appVouch.setShenhr((shenhr.isEmpty() ? "" : ryMap.get(shenhr).toString()));

                log.info("createProcurementProcessNewAction-主表信息，Requestid："+requestID+",Biaoti："+requestname+",Liucbh："+liucbh+",Shenqr："+(shenqr.isEmpty() ? "" :ryMap.get(shenqr).toString())
                        +",Shenqrq："+shenqrq+",Shenqyy："+shenqyy+",Ccode："+liucbh+",Shenhr："+(shenhr.isEmpty() ? "" : ryMap.get(shenhr).toString()));

                //获取流程的明细表数据
                List<JSONObject> list = getJsonArray(requestInfo.getDetailTableInfo().getDetailTable(0));
                log.info("createProcurementProcessNewAction-list明细信息 : " + list);
                int j = list.size();
                log.info("j : " + j);
                log.info("company == '7' : " + (company == "7"));//false
                log.info("company.equals('7'): " + company.equals("7"));//true
                //赋值明细
                PuAppVouchBody[] appVouchs = new PuAppVouchBody[j];
                for (int i = 0; i < j; i++) {
                    log.info("i进来了 : " + i + "，company : " + company + "，yzwlbm : " + list.get(i).getString("yzwlbm"));
                    appVouchs[i] = new PuAppVouchBody();
                    appVouchs[i].setWlbm(list.get(i).getString("wlbm1"));//统一取601
                    appVouchs[i].setShul(list.get(i).getString("shul"));
                    appVouchs[i].setDanj("0");
                    appVouchs[i].setJine("0");
                    appVouchs[i].setCgy(list.get(i).getString("xqr").isEmpty() ? "" : ryMap.get(list.get(i).getString("xqr")).toString());
                    appVouchs[i].setBeiz(list.get(i).getString("beiz"));
                    appVouchs[i].setCBusType(list.get(i).getString("ywlx").isEmpty() ? "0" : list.get(i).getString("ywlx"));//0:普通采购,1:委外加工
                    appVouchs[i].setShdz(list.get(i).getString("shdz"));
                    //appVouchs[i].setQwdhq(list.get(i).getString("qwdhsj").isEmpty() ? "" : list.get(i).getString("qwdhsj").replace("-" , ""));
                    appVouchs[i].setQwdhq(list.get(i).getString("qwdhsj").isEmpty() ? "" : list.get(i).getString("qwdhsj"));
                    appVouchs[i].setPuarrivaldate(list.get(i).getString("qwdhrq2").isEmpty() ? "" : list.get(i).getString("qwdhrq2"));
                }
                log.info("转换后公司 : " + mapGs.get(company).toString());

                puApp.setCCompany(mapGs.get(company).toString());//分公司
                puApp.setCptname("生产性物料采购");
                puApp.setAppVouch(appVouch);
                puApp.setAppVouchs(appVouchs);
            }catch (Exception e){
                e.printStackTrace();
                requestInfo.getRequestManager().setMessagecontent("MD05 AppVouch Error "+e.getMessage());
                return FAILURE_AND_CONTINUE;
            }

        }

        String result = "";
        try {
            ServiceForOA workflowServiceXmlLocator = new ServiceForOALocator();//U8接口
            result = workflowServiceXmlLocator.getserviceForOASoap12().addPOVouch(puApp);
        } catch (Exception ex) {
            log.info("输出有值，返回了错误====" + result);
            ex.printStackTrace();
            requestInfo.getRequestManager().setMessagecontent(result);
            return FAILURE_AND_CONTINUE;
        }

        log.info("result====" + result);
        log.info("createProcurementProcessNewAction结束====" + requestID);

        if (result.isEmpty()) {
            return SUCCESS;
        } else {
            requestInfo.getRequestManager().setMessagecontent(result);
            return FAILURE_AND_CONTINUE;
        }

    }

    /**
     * 获取明细表数据
     *
     * @param detailTable
     * @return
     */
    private List getJsonArray(DetailTable detailTable) {
        List<JSONObject> list = new ArrayList<JSONObject>();
        for (Row row : detailTable.getRow()) {
            JSONObject jsonObject = new JSONObject();
            for (Cell cell : row.getCell()) {
                if ("gsgs".equals(cell.getName())) {//归属公司
                    jsonObject.put("ssfygs", cell.getValue());
                } else if ("chbm".equals(cell.getName())) {//存货编码
                    jsonObject.put("wlbm", cell.getValue());
                } else if ("yzwlbm".equals(cell.getName())) {//云智物料编码
                    jsonObject.put("yzwlbm", cell.getValue());
                } else if ("wupmc".equals(cell.getName())) {//物品名称
                    jsonObject.put("wupmc", cell.getValue());
                } else if ("guigxh".equals(cell.getName())) {//规格型号
                    jsonObject.put("guigxh", cell.getValue());
                } else if ("jycgsl".equals(cell.getName())) {//建议采购数量
                    jsonObject.put("shul", cell.getValue());
                } else if ("danw".equals(cell.getName())) {//单位
                    jsonObject.put("danw", cell.getValue());
                } else if ("danj".equals(cell.getName())) {//单价
                    jsonObject.put("danj", cell.getValue());
                } else if ("jine".equals(cell.getName())) {//金额
                    jsonObject.put("jine", cell.getValue());
                } else if ("cgy".equals(cell.getName())) {//采购员
                    jsonObject.put("cgy", cell.getValue());
                } else if ("beiz".equals(cell.getName())) {//备注
                    jsonObject.put("beiz", cell.getValue());
                } else if ("ywlx".equals(cell.getName())) {//业务类型
                    jsonObject.put("ywlx", cell.getValue());
                } else if ("shdz".equals(cell.getName())) {//收货地址
                    jsonObject.put("shdz", cell.getValue());
                } else if ("wlbm1".equals(cell.getName())) {//MC05 物料编码
                    jsonObject.put("wlbm1", cell.getValue());
                } else if ("xqr".equals(cell.getName())) {//MC05 需求人
                    jsonObject.put("xqr", cell.getValue());
                } else if ("xq".equals(cell.getName())) {//MC06 需求人
                    jsonObject.put("xq", cell.getValue());
                }  else if ("qwdhsj".equals(cell.getName())) {//期望到货时间
                    jsonObject.put("qwdhsj", cell.getValue());
                }else if ("qwdhrq2".equals(cell.getName())) {//期望到货时间
                    jsonObject.put("qwdhrq2", cell.getValue());
                }
            }
            list.add(jsonObject);
        }
        return list;
    }

}
